import {
  dom,
  _closest
} from './dom.js'
import {
  emit
} from './eventBus.js'
import {
  _checkbox
} from './checkbox.js'
import {
  deleteProperty,
  changeProperty
} from '../utils/index.js'


// 表格
export const _grid = (options = {}, data = [], events = {}) => {
  let {
    fields,
    statis,
    props
  } = options

  // 删除属性
  fields = fields.map(t => {
    t = changeProperty(t, 'field', 'name')
    deleteProperty(t, 'placeholder')
    return t

  })


  let thead = _gridHead(fields)
  let tbody = _gridBody(fields, data)
  let children = [thead, tbody]
  if (statis) {
    let tfoot = _gridFoot(fields, data, statis)
    children.push(tfoot)
  }

  return dom.table(children, {
    cellspacing: 0,
    cellpadding: 0,
    border: 0,
    ...props
  }, events)


}
// 表头
const _gridHead = (fields = []) => {
  let cols = fields.map(t => {
    let label = t.label
    let type = t.type
    switch (type) {
      case 'selection':
        label = _checkbox('', {}, {
          click: () => {
          }
        })
        break;
      default:
        label = t.label
    }

    delete t.label
    return dom.th(label, t)
  })
  let tr = dom.tr(cols)
  let thead = dom.thead(tr)
  return thead
}
// 表体
const _gridBody = (fields = [], data = []) => {
  let rows = data.map((row, rowIndex) => _gridRows(fields, row, rowIndex));
  return dom.tbody(rows)
}

// 行
export const _gridRows = (fields = [], row = {}, rowIndex = 0) => {
  let cols = fields.map(t => {
    let type = t.type
    let key = t.field || t.name || ""
    let value = row[key] || ""
    let text
    switch (type) {
      case 'index':
        text = row.index || rowIndex + 1
        break;
      case 'selection':
        text = _checkbox('')
        t.class = 'center'
        break;
      case 'operation':
        text = t.options.map(op => {
          let btn = dom.div(op.label, {
            class: op.name
          }, (e) => {
            let tr = _closest(btn, "tr"),
              table = _closest(tr, "table");
            op.click(e, {
              row,
              rowIndex,
              btn,
              tr,
              table,
              emit //事件
            })
          })
          return btn
        })
        break
      default:
        text = value
    }
    return dom.td(text, t)
  })
  return dom.tr(cols)
}
// 表尾
export const _gridFoot = (fields = [], data = [], statis = {}) => {
  const statisFields = statis.fields
  // 合计
  const getsum = (field) => {
    return data.reduce((a, b) => {
      return a + b[field]
    }, 0)
  }

  let cols = fields.map((t, index) => {
    let label = ''
    if (index === 0) {
      label = statis.label
    } else {
      let field = t.field || t.name || ""
      if (statisFields.includes(field)) {
        label = getsum(field)
      }
    }
    return dom.td(label, t)
  })
  let tr = dom.tr(cols)
  let tfoot = dom.tfoot(tr)
  return tfoot

}

